package com.foton.logistic.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.foton.logistic.R;
import com.foton.logistic.base.BaseActivity;
import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.image.ImageChooseUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.ImageCaptureManager;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.StringUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


/**
 * Created by wuhaocong on 2017/7/5.
 */

@RuntimePermissions
public class PictureActivity extends BaseActivity {

    private ImageCaptureManager captureManager; // 相机拍照处理类
    private ImageView chooseIv;
    private boolean isTakePhoto = true;
    private LinearLayout linearLayout;
    private LinearLayout ll_card_fm;
    private int type;
    private ImageView choosef;
    private ImageView chooseDivedFm;
    private ImageView chooseDivedZm;
    private LinearLayout llDricerCardZ;
    private LinearLayout llDriverCardF;
    private String picture1;
    private String picture2;
    private String picture3;
    private String picture4;
    private ArrayList<String> mSelPhotos=new ArrayList<>();
    private String regTel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ft_ui_picture);
        ButterKnife.inject(this);
        chooseIv = (ImageView) findViewById(R.id.idCard_zm_im);
        choosef = (ImageView) findViewById(R.id.idCard_fm_im);
        chooseDivedFm = (ImageView) findViewById(R.id.diveCard_fm_im);
        chooseDivedZm = (ImageView) findViewById(R.id.diveCard_zm_im);
        linearLayout = (LinearLayout) findViewById(R.id.idCard_zm);
        llDricerCardZ = (LinearLayout) findViewById(R.id.jiashi_zm);
        ll_card_fm = (LinearLayout) findViewById(R.id.idCard_fm);
        llDriverCardF = (LinearLayout) findViewById(R.id.jiashi_fm);
        //regTel =SharedUtil.getRegTel(this);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureActivityPermissionsDispatcher.checkWithCheck(PictureActivity.this);
                type = 1;
            }
        });
        ll_card_fm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureActivityPermissionsDispatcher.checkWithCheck(PictureActivity.this);
                type = 2;
            }
        });
        llDricerCardZ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureActivityPermissionsDispatcher.checkWithCheck(PictureActivity.this);
                type = 3;
            }
        });
        llDriverCardF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureActivityPermissionsDispatcher.checkWithCheck(PictureActivity.this);
                type = 4;
            }
        });
    }

    @Override
    public void init() {
        setBackLayoutVisibility(View.VISIBLE);
        setTitleText("上传证件");
        setTitleTextVisibility(View.VISIBLE);
    }

    public void delFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    private void takePhoto() {
        try {
            if (captureManager == null) {
                captureManager = new ImageCaptureManager(PictureActivity.this);
            }
            Intent intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            Toast.makeText(PictureActivity.this, "无法启用系统相机", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:

                    if (captureManager.getCurrentPhotoPath() != null) {
                        isTakePhoto = false;
                        captureManager.galleryAddPic();
                        Log.e("URL", captureManager.getCurrentPhotoPath());
                        if (type == 1) {
                            chooseIv.setVisibility(View.VISIBLE);
                            Glide.with(PictureActivity.this)
                                    .load(captureManager.getCurrentPhotoPath())
                                    .asBitmap()
                                    .into(chooseIv);
                            picture1 = ImageChooseUtil.saveScaleImageNoWater(captureManager.getCurrentPhotoPath()) ;
                            mSelPhotos.add(picture1);

                            LogUtil.e("kingbluez" + captureManager.getCurrentPhotoPath());
                        } else if (type == 2) {
                            choosef.setVisibility(View.VISIBLE);
                            Glide.with(PictureActivity.this)
                                    .load(captureManager.getCurrentPhotoPath())
                                    .asBitmap()
                                    .into(choosef);
                            picture2 = ImageChooseUtil.saveScaleImageNoWater(captureManager.getCurrentPhotoPath());
                            mSelPhotos.add(picture2);
                            LogUtil.e("kingbluef" + captureManager.getCurrentPhotoPath());
                        } else if (type == 3) {
                            chooseDivedZm.setVisibility(View.VISIBLE);
                            Glide.with(PictureActivity.this)
                                    .load(captureManager.getCurrentPhotoPath())
                                    .asBitmap()
                                    .into(chooseDivedZm);
                            picture3 = ImageChooseUtil.saveScaleImageNoWater(captureManager.getCurrentPhotoPath());
                            mSelPhotos.add(picture3);
                            LogUtil.e("kingbluef" + captureManager.getCurrentPhotoPath());
                        } else if (type == 4) {
                            chooseDivedFm.setVisibility(View.VISIBLE);
                            Glide.with(PictureActivity.this)
                                    .load(captureManager.getCurrentPhotoPath())
                                    .asBitmap()
                                    .into(chooseDivedFm);
                            picture4 = ImageChooseUtil.saveScaleImageNoWater(captureManager.getCurrentPhotoPath());
                            mSelPhotos.add(picture4);
                            LogUtil.e("kingbluef" + captureManager.getCurrentPhotoPath());
                        }
                    }
                    break;
            }
        }
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void check() {
        if (captureManager == null) {
            captureManager = new ImageCaptureManager(PictureActivity.this);
        }
        takePhoto();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PictureActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnClick(R.id.ft_ui_register)
    public void onViewClicked() {
        requestData();

    }
    private void requestData() {
        String uploadImagePath = null;
        if (mSelPhotos.size()<4) {
            OptionUtil.addToast(this, "请上传四张完整证件照");
            return;
        } else {
            for (String imagePath : mSelPhotos) {
                if (StringUtil.isEmpty(uploadImagePath)) {
                    uploadImagePath = imagePath;
                } else {
                    uploadImagePath = uploadImagePath + "," + imagePath;
                }
            }
        }
        List<File> fileList = OptionUtil.getImageList(uploadImagePath);
        Map<String, Object> argMap = HttpUtil.getEncryMap1();
        argMap.put("tel", SharedUtil.getRegTel(this));
        argMap.put("confirmCode", SharedUtil.getCode(this));
        argMap.put("password", SharedUtil.getPassword(this));
        argMap.put("carType", SharedUtil.getCarType(this));
        argMap.put("name", SharedUtil.getName(this));
        argMap.put("gender", SharedUtil.getGender(this));
        argMap.put("idCard", SharedUtil.getSf(this));
        argMap.put("driverLicense", SharedUtil.getJsCard(this));
        LogUtil.e("+++++"+argMap);
        ShowDialogTask task = new ShowDialogTask(this, taskTag, titleText, getString(R.string.task3), true,
                BaseConstant.REGISTER, argMap, fileList, TaskConstant.UPLOADS);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
               // SharedUtil.saveRegTel1(PictureActivity.this,regTel);
                SharedUtil.saveCarType(PictureActivity.this,"");
                SharedUtil.saveRegTel(PictureActivity.this,"");
                SharedUtil.saveCode(PictureActivity.this,"");
                SharedUtil.savePassword(PictureActivity.this,"");
                SharedUtil.saveCarrierId1(PictureActivity.this,"");
                SharedUtil.saveName(PictureActivity.this,"");
                SharedUtil.saveGender(PictureActivity.this,"");
                SharedUtil.saveSf(PictureActivity.this,"");
                SharedUtil.saveJsCard(PictureActivity.this,"");
                OptionUtil.addToast(BaseApplication.self(),"注册成功,等待审核通过");
                //BaseConstant.COMPUL=false;
                screenManager.closeAppoin(RegisterActivity.class);
                //screenManager.closeAppoin(SelectActivity.class);
                screenManager.closeAppoin(SupplyActivity.class);
                Intent intent=new Intent(PictureActivity.this,LoginActivity.class);
                startActivity(intent);
                finishSelf();

            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();

    }
}
